$(function() {
    var cols=6;
	var rows_delete=0;
	var mode="add";
	var m_id=0;
    var url='controls/class_model.php';
   
	//LoadData(0);
	 if (_dd==1){
		$("#btnAdd").show();
	}else{
		$("#btnAdd").hide();
	}
	
	 $.get(url, {"m":"year"},function(data){
			var cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					$("#cboYear_Search,#cboYear").append(
						$('<option></option>').val(text).html(text)
					);
				});
				$.get(url,{"m":"curryear"},function(data){
					$("#cboYear_Search,#cboYear").val(data);
					LoadData(data,0);
				});
			}
			
	});
		
	 function LoadData(year,id){
        $( "#resultData tbody tr" ).remove();
 
        
        $('#resultData').dataTable( {
			"bProcessing": true,
			"bFilter": false,
			"bLengthChange": false,
			 "bAutoWidth": false,
			"sAjaxSource": url,
			"oLanguage": {
				"sEmptyTable":     "ไม่พบข้อมูล"
			},
			"bDestroy": true,
			"sServerMethod": "POST",
			"fnServerParams": function ( aoData ) {
					aoData.push( { "name": "m", "value": "load" },
								{"name":"id","value":id},
								{"name":"year","value":year}
							);
				},
			"aoColumnDefs":[
				{  "bVisible": false , "aTargets": [ 1 ] },	
				{  "bVisible": false , "aTargets": [ 2 ] },	
				{   "bSortable": true, "aTargets": [ 3 ] ,"sClass":"text-center"},	
				{   "bSortable": true, "aTargets": [ 4 ] ,"sClass":"left"},	
				{   "bSortable": true, "aTargets": [ 5 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 6 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 7 ] ,"sClass":"text-left" },	
				{   "bSortable": true, "aTargets": [ 8 ] ,"sClass":"text-left" },	
				{   "bSortable": true, "aTargets": [ 9 ], "sClass":"center",
					"mRender": function ( data, type, full ) {
						var tmp="";
						if (data=='Y')
							tmp="<font style='color:green !important;'>ใช้งาน</font>";
						else
							tmp="<font style='color:red !important;'>ยกเลิก</font>";
						return tmp;}
				},
				{  "bVisible": false , "aTargets": [ 10 ] },	
				{  "bVisible": false , "aTargets": [ 11 ] },	
				{ "aTargets": [ 12 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						if (_it==1)
						return "<a href='#popup' data-toggle='modal'><img src='img/edit-file.png' class='btnEdit' style='cursor:pointer;'/></a>";
						else
						return "";
						}
				},
				{"aTargets": [ 13 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						if (_te==1)  
						return "<a href='#popupConfirm' data-toggle='modal'><img src='img/delete-file.png' class='btnDel' style='cursor:pointer;'/></a>";
						else 
						return "";
					}
				}
			],"fnDrawCallback": function ( oSettings ) {
				 var that = this;
				/* Need to redo the counters if filtered or sorted */
                 var iTotalRecords = oSettings.fnRecordsTotal();
				//alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);
				 
					if (iTotalRecords > 0){ 	
						if ( oSettings.bSorted || oSettings.bFiltered )
						{
							for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
							{
								$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
							}
						}
					}
					 
				} 
		 } );
		 
      }
	$.get(url, {"m":"c"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					
					$("#cboClassLevel").append(
							$('<option></option>').val(text).html(index)
						 );
					$("#cboClassLevel_Search").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
	});
	
	$.get(url, {"m":"emp"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					
					$("#cboTeacher1,#cboTeacher2").append(
							$('<option></option>').val(index).html(text)
						 );
					 
				});
			}
	});
	
	$("#cboClassLevel_Search,#cboTeacher1,#cboTeacher2").append($('<option></option>').val(0).html(''));
	
	$("#btnSearch").click(function(){
		var _class_level = $("#cboClassLevel_Search").val();
		var _year = $("#cboYear_Search").val();
		LoadData(_year,_class_level);
	});
	
	$("#txtAmount").keypress(function(e){
		
		if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
			return false;
		}
	});
	
	$("#btnSave").live('click',function(){
		$("input").not("[type=submit]").jqBootstrapValidation({preventSubmit: false,
			submitSuccess: function ($form, event) { event.preventDefault();}
		}); 
		var _year = $("#cboYear").val();
		var _level = $.trim($("#cboClassLevel").val());		
		var _room = $("#txtRoom").val();
		var _amt = $("#txtAmount").val();
		var _t1 = $("#cboTeacher1").val();
		var _t2 = $("#cboTeacher2").val();
		var dataSet;
		 
		if (mode=="add"){
			dataSet={"m":"add","year":_year,"level":_level,"room":_room ,"amt":_amt,"s":$('input[name=chk]:checked').val(),'teacher_1':_t1,'teacher_2':_t2};  
		}else{
			dataSet={"m":"edit","year":_year,"id":m_id,"level":_level,"room":_room ,"amt":_amt,"s":$('input[name=chk]:checked').val(),'teacher_1':_t1,'teacher_2':_t2};   
		}
		if (_level!=""){
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
					$("#popup").modal('hide');
					$("#btnSearch").click();
					//LoadData();
				}
			});
			
		}
		 $("input").jqBootstrapValidation("destroy");
	});		
	 
	$("#btnAdd").live('click', function(){
		mode="add";
		$("#txtRoom , #txtAmount").val('');
	});
		
	//Popup confirm delete
	$(".btnDel").live('click',function(){
		var rows = $(this).closest("tr").get(0);
		rows_delete = $('#resultData').dataTable().fnGetPosition(rows);

	}); 
	
	$("#btnDelete").live('click', function(){
		var row_id =$('#resultData').dataTable().fnGetData(rows_delete);
		
		var id=row_id[1];
		 
		 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"del","id":id},
				 success: function(data){
					$("#popupConfirm").modal('hide');
					$('#resultData').dataTable().fnDeleteRow( rows_delete );
					$('#resultData').dataTable().fnDraw();
				 }
			 });
 
	}); 
	$("#btnPrintDraft").click(function(){
	  $("#resultData").printThis();
		return false;
           
	});
	$(".btnEdit").live('click',function(){
		mode="edit";
		var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
		var data =$('#resultData').dataTable().fnGetData(rows);
		 
		m_id = data[1];
	
		$("#cboClassLevel").val(data[3]);//.filter("[value="+data[2]+"]").attr("selected","selected");
		
		$("#txtAmount").val(data[6]);
		$("#txtRoom").val(data[5]);
		$("#cboTeacher1").val(data[10]);
		$("#cboTeacher2").val(data[11]);
		if (data[9]=='Y'){
			$("#chkY").attr('checked','checked');
		}else{
			$("#chkN").attr('checked','checked');
		}
	});
	  
    
});


